﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.DataModel;
using S3.Biz;
using S3.Common;

namespace S3
{
    public partial class ManageAdditionalItem : S3FormBase
    {        
        private bool _isChanged;

        public ManageAdditionalItem()
        {
     
            InitializeComponent();

            LoadData();
        }

        private void LoadData()
        {
 //           gridServicesList.AutoGenerateColumns = false;
            var manager = new GoodsStoreManager();
            IQueryable<GoodsStore> list = manager.GetAll();
            if (list != null && list.Count() > 0)
            {
                //List<ExtendService> newList = new List<ExtendService>();

                //foreach (var item in list)
                //{
                //    ExtendService service = new ExtendService()
                //    {
                //        ItemName = item.ItemName,
                //        UnitPrice = Utils.StringFormatMoney(item.UnitPrice),
                //        Status = item.Status
                //    };
                //    newList.Add(service);

                //}

                //gridServicesList.DataSource = list;
                gridControl1.DataSource = list;
                
            }
        }

        private void gridService_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0)
                {
                    //Check duplicate service name
                    if (e.ColumnIndex == 0)
                    {
                        string strServiceName = gridServicesList.Rows[e.RowIndex].Cells[0].Value + "";
                        //string strUnitPrice = gridServicesList.Rows[e.RowIndex].Cells[1].Value + "";
                        //string strStatus = gridServicesList.Rows[e.RowIndex].Cells[2].Value + "";


                        if (!string.IsNullOrEmpty(strServiceName))
                        {
                            for (int i = 0; i < gridServicesList.Rows.Count - 1; i++)
                            {
                                if (gridServicesList.Rows[i].Cells[0].Value != null && i != e.RowIndex &&
                                    strServiceName.Trim().ToLower() ==
                                    gridServicesList.Rows[i].Cells[0].Value.ToString().ToLower())
                                {
                                    gridServicesList.Rows[e.RowIndex].Cells[0].Value = "";
                                    XtraMessageBox.Show("Đã tồn tại dịch vụ " + strServiceName);
                                    gridServicesList.Rows[e.RowIndex].Cells[0].Selected = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (!_isChanged)
                    {
                        _isChanged = true;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult result =
                XtraMessageBox.Show("Viec nay co the se anh huong den du lieu cac may dang choi. Ban van muon luu?", "Chu y",
                                MessageBoxButtons.YesNo);
            if (result != DialogResult.Yes) return;

            var listItems = new List<GoodsStore>();
            for (int i = 0; i < gridServicesList.Rows.Count; i++)
            {
                string strServiceName = gridServicesList.Rows[i].Cells[0].Value + "";
                string strUnitPrice = gridServicesList.Rows[i].Cells[1].Value + "";
                string strStatus = ItemStatusValue.Text[ItemStatus.Avaiable];
                decimal unitPrice = 0;

                //Check
                if (!string.IsNullOrEmpty(strServiceName) && decimal.TryParse(strUnitPrice, out unitPrice) &&
                    !string.IsNullOrEmpty(strStatus))
                {
                    //Save
                    var item = new GoodsStore
                                   {
                                       ItemName = strServiceName,
                                       UnitPrice = unitPrice,
                                       Status = strStatus
                                   };

                    //Add to list
                    listItems.Add(item);
                }
            }

            if (listItems.Count > 0)
            {
                using (var additionalItemUnitPriceManager = new GoodsStoreManager())
                {
                    additionalItemUnitPriceManager.DeleteAll();
                    additionalItemUnitPriceManager.SaveAll(listItems);
                }
            }
            _isChanged = true;
            Close();
        }
   
        /// <summary>
        /// Close form if click ESC
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>

        private void ManageAdditionalItem_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }

        #region ProcessCmdKey

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                if (msg.WParam.ToInt32() == (int) Keys.Escape)
                {
                    Close();
                }
                else
                {
                    return base.ProcessCmdKey(ref msg, keyData);
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show("Key Overrided Events Error:" + Ex.Message);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                if (e.RowHandle >= 0)
                {
                    
                    //Check duplicate service name
                    {
                        string strServiceName = e.Value + "";
                        //string strUnitPrice = gridServicesList.Rows[e.RowIndex].Cells[1].Value + "";
                        //string strStatus = gridServicesList.Rows[e.RowIndex].Cells[2].Value + "";


                        if (!string.IsNullOrEmpty(strServiceName))
                        {
                            for (int i = 0; i < gridView1.RowCount - 1; i++)
                            {
                                if (gridView1.GetRowCellValue(i, e.Column) != null && i != e.RowHandle &&
                                    strServiceName.Trim().ToLower() ==
                                    gridView1.GetRowCellValue(i, e.Column).ToString().ToLower())
                                {
                                    gridView1.SetRowCellValue(e.RowHandle, e.Column, "");
                                    XtraMessageBox.Show("Đã tồn tại dịch vụ " + strServiceName);
                                    gridView1.SelectRow(e.RowHandle);
                                    break;
                                }
                            }
                        }
                    }

                    if (!_isChanged)
                    {
                        _isChanged = true;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
    }
}